package com.example.backend.repository;

import com.example.backend.domain.entity.TicketAttachment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface TicketAttachmentRepository extends JpaRepository<TicketAttachment, Long> {
    
    List<TicketAttachment> findByTicketIdOrderByCreatedAtDesc(Long ticketId);
    
    List<TicketAttachment> findByTicketIdAndIsPublicTrueOrderByCreatedAtDesc(Long ticketId);
    
    List<TicketAttachment> findByUploadByIdOrderByCreatedAtDesc(Long uploadById);
    
    @Query("SELECT a FROM TicketAttachment a WHERE a.ticket.id = :ticketId AND a.fileType = :fileType ORDER BY a.createdAt DESC")
    List<TicketAttachment> findByTicketIdAndFileType(@Param("ticketId") Long ticketId, @Param("fileType") String fileType);
    
    @Query("SELECT a FROM TicketAttachment a WHERE a.fileName = :fileName AND a.ticket.id = :ticketId")
    Optional<TicketAttachment> findByFileNameAndTicketId(@Param("fileName") String fileName, @Param("ticketId") Long ticketId);
    
    @Query("SELECT COUNT(a) FROM TicketAttachment a WHERE a.ticket.id = :ticketId")
    Long countByTicketId(@Param("ticketId") Long ticketId);
    
    @Query("SELECT SUM(a.fileSize) FROM TicketAttachment a WHERE a.ticket.id = :ticketId")
    Long getTotalSizeByTicketId(@Param("ticketId") Long ticketId);
}
